import { ref } from "vue"
import { sendCode } from '@/api/index'
import { ElMessage } from "element-plus";

export default (reg_data, reg_data_ref) => {

    // 获取验证码
    const dialogVisible = ref(false);
    const codePhone = ref("");
    const handleSendCode = async (phone) => {
        let res = await sendCode({ phone });
        if (res.success) {
            dialogVisible.value = true;
            codePhone.value = res.entity;
            ElMessage.success(res.message);
        } else {
            ElMessage.error(res.message);
        }
    };

    // 60秒验证码
    const btnText = ref("获取验证码");
    const countdown = ref(60);
    const disabled = ref(true);

    const handleCoundDown = (phone) => {
        if (reg_data.value.code == "") {
            ElMessage.error("请填写验证码");
            return;
        }
        if (disabled.value) {
            return; // 如果按钮已禁用，则不执行任何操作
        }

        handleSendCode(phone);
        let timer = setInterval(() => {
            if (countdown.value <= 0) {
                disabled.value = false;
                btnText.value = "获取验证码";
                clearInterval(timer);
                countdown.value = 60;
            } else {
                btnText.value = countdown.value + "s 后重试";
                countdown.value--;
                disabled.value = true;
            }
        }, 1000);
    };


    // 必须判断成功后才可以点击获取验证码
    const changePhone = () => {
        reg_data_ref.value.validate(async (valid, roles) => {
            if (!roles.phone) {
                disabled.value = false;
            } else {
                disabled.value = true;
            }
        });
    };

    return { handleCoundDown, changePhone, codePhone, dialogVisible, btnText, countdown, disabled }
}



